#include "xcamera_record.h"
#include "xdemux_task.h"
#include "xmux_task.h"
#include <chrono>
#include <iomanip>
using namespace std;
using namespace chrono;

/// 生成存储的文件名
/// \brief GetFileName
/// \return
///
static string GetFileName(const string &path) {
  auto t = system_clock::to_time_t(system_clock::now());
  stringstream ss;
  auto time_str = put_time(localtime(&t), "%Y_%m_%d_%H_%M_%S");
  ss << path << "/" << "cam_" << time_str << ".mp4";
  return ss.str();
}

void XCameraRecord::Main() {
  XDemuxTask demux;
  if (rtsp_url_.empty()) {
    LOGERROR("open rtsp url failed!");
    return;
  }
  while (!is_exit()) {
    if (demux.Open(rtsp_url_)) { // 最坏情况阻塞1s
      break;
    }
    std::this_thread::sleep_for(3s);
    continue;
  }

  auto vpara = demux.CopyVideoPara();
  if (!vpara) {
    LOGERROR("demux.CopyVideoPara failed!");
    // 线程池还没有启动，需要考虑资源释放问题
    demux.Stop();
    return;
  }
  demux.Start();
  auto apara = demux.CopyAudioPara();
  AVCodecParameters *para = nullptr; // 音频参数
  AVRational *timebase = nullptr;    // 音频时间基数
  // if (apara) {
  //   para = apara->para;
  //   timebase = apara->time_base;
  // }
  XMuxTask mux;
  if (!mux.Open(GetFileName(save_path_).c_str(), vpara->para,
                vpara->time_base, // 视频参数
                para, timebase    // 音频参数
                )) {
    LOGERROR("mux.Open save_path_ failed!");
    demux.Stop();
    mux.Stop();
    return;
  }
  demux.set_next(&mux);
  mux.Start();
  auto cur = NowMs();
  while (!is_exit_) {
    if (NowMs() - cur > file_sec_ * 1000) {
      cur = NowMs();
      mux.Stop(); // 停止存储，
      if (!mux.Open(GetFileName(save_path_).c_str(), vpara->para,
                    vpara->time_base, // 视频参数
                    para, timebase    // 音频参数
                    )) {
        LOGERROR("mux.Open save_path_ failed!");
        demux.Stop();
        mux.Stop();
        return;
      }
      mux.Start();
    }
    std::this_thread::sleep_for(10ms);
  }
  mux.Stop();
  demux.Stop();
}
